package yt.demo.appcommonbean.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import yt.demo.appcommonbean.http.ResponseCode;
import yt.demo.appcommonbean.http.RestResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<RestResponse<Map<String, String>>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
         List<String> msgs =new ArrayList<>();
         ex.getBindingResult().getFieldErrors().forEach(error -> {
            errors.put(error.getField(), error.getDefaultMessage());
            msgs.add(error.getDefaultMessage());
        });
        RestResponse<Map<String, String>> response = RestResponse.fail("验证失败："+ msgs.getFirst(), errors);
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(LogicException.class)
    public ResponseEntity<RestResponse<String>> handleLogicException(LogicException ex) {
        RestResponse<String> response;
        if (ex.getCode() != null) {
            response = RestResponse.fail(ex.getCode());
        } else {
            response = RestResponse.fail(ex.getMessage(), null);
        }
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(NotLoginException.class)
    public ResponseEntity<RestResponse<String>> handleLogicException(NotLoginException ex) {
        RestResponse<String> response;
        if (ex.getMessage() != null) {
            response = RestResponse.fail(ResponseCode.AUTH_NOT_LOGIN);
        } else {
            response = RestResponse.fail(ex.getMessage(), null);
        }
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(NotPermissionException.class)
    public ResponseEntity<RestResponse<String>> handleLogicException(NotPermissionException ex) {
        RestResponse<String> response;
        if (ex.getMessage() != null) {
            response = RestResponse.fail(ResponseCode.AUTH_NOT_PERMISSION);
        } else {
            response = RestResponse.fail(ex.getMessage(), null);
        }
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }


}
